<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <!--
      :data="departments" - 绑定数据
      highlight-current-row - 当前行高亮
      v-loading="listLoading" - 加载框=盲等框
      @selection-change="selsChange" - 选中时间
      sortable - 是否显示排序图标
    -->
		<el-table :data="departments" highlight-current-row
              v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" >
			</el-table-column>
			<el-table-column prop="dirPath" label="部门路径" width="100" >
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" >
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: green">启用</span>
          <span v-else style="color: red">禁用</span>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" width="120" >
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" min-width="120" >
			</el-table-column>
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条：批量删除和分页栏-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增和修改对话框-->
    <!--
      :title="title" - 标题
      :visible.sync="saveFormVisible" - 是否显示对话框 - 默认不显示
      :close-on-click-modal="false" - 在对话框外面点击不关闭
      :model="saveForm" - 绑定表单
      label-width="80px" - 宽度
      :rules="saveFormRules" - 表单的验证规则
      ref="saveForm" - 为当前对话框取名 - 方便验证表单
    -->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="100px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门经理">
          <!--
              v-for="item in managers" - 遍历的所有的t_employee
              :label="item.username" - 显示username
              :value="item.id" - 传递数据 id

              回显机制：
                v-model="saveForm.manager_id"  根据这个id 和 item中对象的id对比
          -->
          <el-select v-model="saveForm.manager_id" clearable placeholder="请选择">
            <el-option
                v-for="item in managers"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>
				<el-form-item label="上级部门">
          <!--<el-input v-model="saveForm.parent_id"></el-input>-->
          <!--
            v-model="saveForm.parent_id" - 绑定数据 - 做回显 - 传值
              :options="deptTree" - 需要回显的部门数
              :props="{ checkStrictly: true,label:'name',value:'id' }"
                  label:'name' - 显示哪一个值
                  value:'id' - 传递数据
              clearable - 可清理的
          -->
          <el-cascader v-model="saveForm.parent_id"
                       :options="deptTree"
                       :props="{ checkStrictly: true,label:'name',value:'id' }"
                       clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

	export default {
	  //定义数据模型
		data() {
			return {
			  //1.数据列表展示
        departments: [],    //列表数据
        listLoading: false, //加载框 - 默认不显示

        //2.分页查询数据
        totals: 0,
        currentPage: 1,
        pageSize: 5,

        //3.高级查询
        keyword:'',

        //4.批量删除
        sels: [],//列表选中列

        //5.添加或修改
        title: '',
        saveFormVisible: false,//添加和修改对话框的显示
        saveLoading: false,//保存盲等框 - 在提交按钮上
        saveFormRules:{//表单项验证规则
          name:[
            {required: true,message:'请输入部门名称',trigger:'blur'}
          ],
          sn:[
            {required: true,message:'请输入部门编号',trigger:'blur'}
          ]
        },
        //编辑界面数据：建议字符串用‘’,id用null
        saveForm:{
          id:null,
          sn:'',
          name:'',
          state: 1,
          manager_id:null,
          parent_id:null
        },
        //查询所有的经理
        managers:[],
        //查询部门数
        deptTree:[],
			}
		},
    //定义方法
		methods: {
      //1.获取部门列表
      getDepartments() {
        //参数
        let para = {
          "currentPage": this.currentPage,
          "pageSize": this.pageSize,
          "keyword": this.keyword
        };
        //显示盲等框
        this.listLoading = true;
        this.$http.post("/department",para).then(res=>{
          //关闭盲等框
          this.listLoading = false;
          //显示分页数据
          this.departments = res.data.data;
          //计算分页栏
          this.totals = res.data.totals;
        }).catch(res=>{
          this.$message.error('网络错误，请稍后再试');
        })
      },

      //2.点击当前页的逻辑
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getDepartments();
      },

      //3.高级查询
      keywordQuery(){
        //将当前页重置为1，然后重新查询
        this.currentPage = 1;
        this.getDepartments();
      },

      //4.删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {//确认框
          type: 'warning'
        }).then(() => {//点击确认的时候
          this.listLoading = true;
          this.$http.delete("/department/"+row.id).then(res=>{
            this.listLoading = false;//关闭盲等框
            if (res.data.success){//成功
              this.$message.success("删除成功");
              //对当前页的处理
              let totalPage = Math.ceil(this.totals/this.pageSize);//算出总页数
              //如果当前页是最后一页                     并且是最后一条数据
              if (this.currentPage==totalPage &&(this.totals-1)%this.pageSize==0
                  //不是第一页
                  && this.currentPage!=1){
                this.currentPage=this.currentPage-1;
              }
              this.getDepartments();
            }else{
              this.$message.error("网络繁忙,请稍后再试[500]")
            }
          }).catch(res=>{
            this.$message.error("网络繁忙,请稍后再试[400,404]")
          })
        }).catch(() => {//点击取消的时候
        });
      },

      //5.选中改变时触发
      selsChange: function (sels) {
        this.sels = sels;
      },


      //6.批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/department",ids).then(res=>{
            //关闭盲等框
            this.listLoading = false;
            if (res.data.success){
              //弹出成功信息
              this.$message.success("删除成功");
              this.currentPage = 1;
              //重新获取资源
              this.getDepartments();
            }else {
              this.$message.error("网络繁忙，请稍后再试【500】")
            }
          }).catch(res=>{
            this.$message.error("网络繁忙，请稍后再试【400，404】")
          })
        }).catch(() => {
        });
      },

			//7.点击添加按钮显示对话框
			handleAdd: function () {
				this.saveForm = {
				  id:null,
          sn:'',
					name: '',
					state: 1,
					manager_id: null,
					parent_id: null
				};
				this.title = "添加";
        this.getManagers();
				this.getDeptTree();
        //显示对话框
        this.saveFormVisible = true;
			},
      
      //8.点击修改按钮显示对话框
      handleEdit: function (index, row) {
        //回显数据：避免以前的数据发生改变
        this.saveForm = Object.assign({}, row);
        this.title = "修改";
        this.getManagers();
        this.getDeptTree();
        //显示对话框
        this.saveFormVisible = true;
      },
      
			//9.提交添加或修改的数据
			saveSubmit: function () {
        //所有的对话框中的名称为save Form的对话框 验证上面的表单项验证通过就返回true
				this.$refs.saveForm.validate((valid) => {//表单验证
					if (valid) {//表单验证通过
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							let para = Object.assign({}, this.saveForm);
              let arr = para.parent_id;
              if(arr && arr.length==0){
                para.parent_id = null;
              }
              if(arr && arr.length>0){ //[1,13]
                para.parent_id = arr[arr.length-1];
              }
						  this.$http.put("/department",para).then(res=>{
						    //关闭盲等框
                this.saveLoading = false;
                //关闭对话框
                this.saveFormVisible = false;
                if (res.data.success){
                  //弹出成功信息
                  this.$message.success("操作成功");
                  //重新获取新的数据
                  this.getDepartments();
                }else{
                  this.$message.error("网络繁忙，请稍后重试【500】")
                }
              }).catch(res=>{
                this.$message.error("网络繁忙，请稍后重试【400,404】")
              })
							});
						}
					});
			},

      //10.查询所有经理
      getManagers(){
        this.$http.get("/employee").then(res=>{
          this.managers = res.data;
        })
      },

      //11.查询所有的部门
      getDeptTree(){
        this.$http.get("/department/deptTree").then(res=>{
          this.deptTree = res.data;
        })
      }
    },
		mounted() {
		  //页面加载完成自动调用这个方法
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>